class Language {
    private i18n: any;
    private locale_path: any;
    private switch_path: any;
    private loadLocales: Array<string> = []
    private addonLocales: any = {'zh-cn':{}, en:{}}

    constructor(i18n:any) {
        this.i18n = i18n?i18n:useI18n();
        this.locale_path = useLocalePath();
        this.switch_path = useSwitchLocalePath();
    }

    /**
     * 获取当前加载的语言
     */
    public getLoadLocale() {
        return this.i18n.locale;
    }

    /**
     * 获取语言列表
     * @return 多语言数组 [zh,en]
     */
    public getLableLocale() {
        return this.i18n.availableLocales;
    }

    /**
     * 获取语言包数据
     * @param local 语言标识 例如:zh en
     */
    public getLocaleMessage(local:string) {
        return this.i18n.getLocaleMessage(local);
    }

    /**
     * 使用语言包
     * @param val 语言包变量
     * @returns
     */
    public t(val: any) {
        return this.i18n.t(val);
    }

    /**
     * 切换语言
     * @param lang 语言标识 例如:zh en
     */
    public setLocale(lang: string) {
        this.i18n.setLocale(lang);
    }

    /**
     * 获取本地化路径
     * 结合 NuxtLink :to
     * @param path 页面路径 例如: /about
     * @return 路径
     */
    public getLocalePath(path: string) {
        return this.locale_path(path);
    }

    /**
     * 获取切换语言跳转路径
     * 结合 NuxtLink :to
     * @param lang 语言标识 例如:zh en
     * @return 路径
     */
    public getSwitchLocalePath(lang: string) {
        return this.switch_path(lang);
    }

    /**
     * 加载插件语言包
     * @param key 插件标识
     * @param locale 语言 
     */
    private async importAddonLocale (key: string, locale: string) {
        const data = await import(`../addons/${key}/locale/${locale}.json`);
        if (data && data.default) {
            for (const k in data.default) {
                this.addonLocales[locale]['addon_' + key + '.' + k] = data.default[k];
            }
        }
        this.loadLocales.push(`${key}_${locale}`);
    }

    /**
     * 加载插件语言包
     * @param addon 标识 
     * @param locale 语言
     * @returns 
     */
    public async loadAddonLocaleLang(addon: string, locale: string) {
        try {
            // 判断插件标识
            if (addon) {
                if (this.loadLocales.includes(`${addon}_${locale}`)) {
                    this.setLocale(locale);
                    return nextTick();
                }

                await this.importAddonLocale(addon, locale);
                this.i18n.mergeLocaleMessage(locale, this.addonLocales[locale]);
            }

            this.setLocale(locale);
            return nextTick();
        } catch (e) {
            this.setLocale(locale);
            return nextTick();
        }
    }
}

export default Language;
